<template>
  <div class="Batch-opreate-button">
    <el-popover placement="bottom" trigger="click" popper-class="batch-list-summary-popper" v-if="tagList.length">
      <div class="list-summary">
        <el-tag
          v-for="(item, idx) in tagList"
          :key="(filedKey && item[filedKey]) || idx"
          effect="plain"
          closable
          class="tag-item"
          @close="onTabClose(idx, item)">
          {{ (renderSelectItemTitle && renderSelectItemTitle(item, idx)) || item.label || idx + 1 }}
        </el-tag>
        <el-tag class="tag-item remove-all" type="danger" @click="onRemoveAll">移除所有</el-tag>
      </div>
      <div slot="reference" class="batch-count-tips">
        已选 ：
        <span class="selected-count">{{ tagList.length }}</span>
      </div>
    </el-popover>
    <el-popover placement="right" trigger="click" :disabled="tagList.length === 0">
      <slot></slot>
      <div slot="reference">
        <div v-if="$slots.tipsButton">
          <slot name="tipsButton"></slot>
        </div>
        <el-button v-else size="mini" :disabled="tagList.length === 0">批量操作</el-button>
      </div>
    </el-popover>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  name: 'BatchButton',
  props: {
    list: {
      type: Array,
      default: () => [],
    },
    filedKey: {
      type: String,
      default: 'id',
    },
    renderSelectItemTitle: {
      type: Function,
    },
  },
  watch: {
    list: {
      handler(arr) {
        if (arr && arr.length) {
          this.tagList = cloneDeep(arr)
        } else {
          this.tagList = []
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      tagList: [],
    }
  },
  methods: {
    onTabClose(idx, item) {
      this.tagList.splice(idx, 1)
      this.$emit('item-delete', item)
    },
    onRemoveAll() {
      this.$confirm('确定要移除当前所有选择吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const removedItems = this.tagList.splice(0, this.tagList.length)
          this.$emit('all-delete', removedItems)
        })
        .catch(() => {})
    },
  },
}
</script>
<style lang="scss" scoped>
.Batch-opreate-button {
  display: flex;
  align-items: center;
  .batch-count-tips {
    margin: 0 20px 0 10px;
    cursor: pointer;
    .selected-count {
      color: #3b93f7;
    }
  }
}
</style>

<style lang="scss">
.batch-list-summary-popper {
  max-width: 300px;
  .list-summary {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    .tag-item {
      margin: 5px 0;
      &:not(:last-child) {
        margin-right: 10px;
      }
      &.remove-all {
        cursor: pointer;
      }
    }
  }
}
</style>
